﻿package com.gobang.netmode.search;

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.JLabel;

import java.awt.Font;
import java.awt.Graphics;

import javax.swing.JTextField;
import javax.swing.ImageIcon;
import javax.swing.JProgressBar;
import javax.swing.JList;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Vector;
import java.awt.Component;

import javax.swing.Box;
import javax.swing.ListSelectionModel;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;

import com.gobang.gobangui.MainWindowUI;
import com.gobang.netmode.util.ClientDataClass;
import com.gobang.netmode.util.ServerMessage;
import com.gobang.util.uipattern.MyJButton;

import java.awt.event.MouseMotionAdapter;
import java.awt.FlowLayout;

public class SearchJFrameOfWAN extends JFrame  {

	private static final long serialVersionUID = 1L;
	static final int portOfWAN = 36871;// 广域网默认端口
	static final String ServerDomain = "125.217.40.27";//广域网域名
	
	static Vector<String> vectorServer = new Vector<String>();
	static JList serverList = new JList(vectorServer);// 根据vectorServerd的变化刷新list
	public static Vector<ServerMessage> serverMessageVector = new Vector<ServerMessage>(); 
	static String ID;

	MyJButton btnCreateRoom;//创建房间
	MyJButton btnJoinRoom;//加入房间
	MyJButton btnBackMainWindow;//返回主界面
	MyJButton btnUpData;//刷新
	MyJButton nextName;//下一个名字
	public  JProgressBar progressBar;// 进度条
	 int proNumber;//用于记录进度条的编号
	ProgressThread progressThread ;//用于更新进度条的线程
	JLabel lblWorningOfName;//名字输入框提示
	
	
	 private static long setUpTime, setUpTimeOfNow;
	 MyJButton btnConnect;//连接
	 JTextField serverIPTextField ;
     JLabel lblWorningOfServer;//服务器输入框提示
    public static ArrayList<InetAddress> ipList = new ArrayList<InetAddress>(10);// 本机IP地址
 	public static InetAddress realLocalIP = null;

	/*
	 * 广域网特有数据域
	 */
 	ClientDataClass client;
 	SearchOfVisitor searchOfVisitor;

	/*
	 * 界面的组件
	 */     
	
	private JPanel contentPane;
	private JTextField nameTextFiled;
	int windowStartX = (int)(java.awt.Toolkit.getDefaultToolkit().getScreenSize().width)/2 - 550;
	int windowStartY = (int)(java.awt.Toolkit.getDefaultToolkit().getScreenSize().height)/2 - 450;
	private static int mouseOnSceenX, mouseOnSceenY;
	private static int jframeX, jframeY;
	
	private boolean isHide = false;
	public String getNameString() {
		return nameTextFiled.getText();
	}
	@Override
	public void setVisible(boolean b) {
		
		super.setVisible(b);
		if(b){
			if(searchOfVisitor == null ||!searchOfVisitor.isAlive()){
				if(client == null){
					client = new ClientDataClass(getNameString(), realLocalIP, 0, MainWindowUI.getID());
				}else{
					client.setClientName(getNameString());
				}
				updateOfRoom();
				searchOfVisitor = new SearchOfVisitor(this, client);
				searchOfVisitor.start();
			} 
		}

	}

//	public static synchronized void  addProgressBarValue(int countNow){
//		if (countNow == count) {//决定是否可以更新进度条
//			progressBarValue++;
//			progressBar.setValue((int) 100.0 * progressBarValue / 255);
//			try {
//				Thread.sleep(10-(int)(10.0 * progressBarValue / 255));//加速效果
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
//			//			System.out.println(100.0 * progressBarValue / 255);
//			if ((int) 100.0 * progressBarValue / 255 >= 100) {
//				progressBar.setValue(0);
//				progressBarValue = 0;
//			}
//		}
//	}

	public ProgressThread getProgressThread() {
		return progressThread;
	}
	/**
	 * Create the frame.
	 */
	public SearchJFrameOfWAN() {
		setUndecorated(true);
		setBackground(new Color(0, 0, 0, 0));
		ipList = getLocalIP.getLocalIPListInteAddresses();// 获得本地IP
		ipList= getLocalIP.filterIP(ipList);// 过滤IP

		//显示IP
		realLocalIP= ipList.get(0);


		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(windowStartX, windowStartY, 1024, 768);
		contentPane = new JPanel();
		contentPane.setOpaque(false);
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		/*
		 * 主面板
		 */
		JPanel MainPanel = new JPanel(){
			private static final long serialVersionUID = 1L;

			public void paintComponent(Graphics g) {
				super.paintComponent(g);
				Graphics2D g2d = (Graphics2D) g;
				g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
				
				g2d.setColor(new Color(255, 255, 255, 150));
				g2d.fillRoundRect(3, 3, getWidth() - 6, getHeight() - 6, 20, 20);
				
				ImageIcon backGround = new ImageIcon(getClass().getResource("/resources/background/background2.png"));
				g2d.drawImage(backGround.getImage(), 0, 0, this.getWidth(), this.getHeight(), this);
				
				g2d.setColor(Color.darkGray);
				g2d.setStroke(new BasicStroke(2));
				g2d.drawRoundRect(1, 1, getWidth() - 3, getHeight() - 3, 20, 20);
				
				g2d.setFont(new Font("楷体", Font.BOLD, 27));
				g2d.drawString("搜索房间", (getWidth()/2)-50, 35);
			}
		};
		MainPanel.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent arg0) {
				mouseOnSceenX = arg0.getXOnScreen();
				mouseOnSceenY = arg0.getYOnScreen();
				jframeX = getX();
				jframeY = getY();
			}
		});
		MainPanel.addMouseMotionListener(new MouseMotionAdapter() {
			@Override
			public void mouseDragged(MouseEvent arg0) {
				if (getWidth() != (int)java.awt.Toolkit.getDefaultToolkit().getScreenSize().getWidth()) {
					setLocation(jframeX + (arg0.getXOnScreen() - mouseOnSceenX), jframeY + (arg0.getYOnScreen() - mouseOnSceenY));
				}
			}
		});


		/*
		 * 显示服务器的面板
		 */
		JPanel serverPanel = new JPanel();
		serverPanel.setOpaque(false);

		JPanel serverListPanel = new JPanel();
		serverListPanel.setOpaque(false);
		/*
		 * 进度条
		 */

		JPanel roomInformationAndProgressBarPanel = new JPanel();
		roomInformationAndProgressBarPanel.setOpaque(false);
		progressBar = new JProgressBar();
		progressBar.setPreferredSize(new Dimension(0,8));
		
		progressBar.setForeground(new Color(65, 120, 225));

		JPanel buttonPanel = new JPanel();
		buttonPanel.setOpaque(false);

		JPanel roomInformationPanel = new JPanel();
		roomInformationPanel.setFont(new Font("宋体", Font.PLAIN, 24));
		roomInformationPanel.setOpaque(false);
		roomInformationPanel.setOpaque(false);

		JLabel lblNewLabel = new JLabel("房间");
		lblNewLabel.setForeground(Color.BLACK);
		lblNewLabel.setFont(new Font("新宋体", Font.BOLD, 24));

		Component horizontalStrut_1 = Box.createHorizontalStrut(50);

		JLabel lblNewLabel_1 = new JLabel("房主");
		lblNewLabel_1.setForeground(Color.BLACK);
		lblNewLabel_1.setFont(new Font("新宋体", Font.BOLD, 24));

		Component horizontalStrut_2 = Box.createHorizontalStrut(60);

		JLabel lblNewLabel_2 = new JLabel("人数");
		lblNewLabel_2.setForeground(Color.BLACK);
		lblNewLabel_2.setFont(new Font("新宋体", Font.BOLD, 24));

		Component horizontalStrut_3 = Box.createHorizontalStrut(100);

		JLabel lblNewLabel_3 = new JLabel("对战双方");
		lblNewLabel_3.setForeground(Color.BLACK);
		lblNewLabel_3.setFont(new Font("新宋体", Font.BOLD, 24));

		Component horizontalStrut_4 = Box.createHorizontalStrut(160);

		JLabel lblNewLabel_4 = new JLabel("状态");
		lblNewLabel_4.setForeground(Color.BLACK);
		lblNewLabel_4.setFont(new Font("新宋体", Font.BOLD, 24));

		Component horizontalStrut_7 = Box.createHorizontalStrut(120);

		btnUpData = new MyJButton();
		btnUpData.setText("刷新");
		btnUpData.setFont(new Font("新宋体", Font.PLAIN, 25));
		btnUpData.addMouseListener(new UpdataActionOfWAN());
		serverList.setOpaque(false);
		serverList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		serverList.setBackground(Color.WHITE);
		serverList.setFont(new Font("楷体", Font.PLAIN, 29));
		serverList.setBorder(new LineBorder(new Color(192,192,250)));
		GroupLayout gl_serverListPanel = new GroupLayout(serverListPanel);
		gl_serverListPanel.setHorizontalGroup(
			gl_serverListPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_serverListPanel.createSequentialGroup()
					.addGroup(gl_serverListPanel.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_serverListPanel.createSequentialGroup()
							.addGap(115)
							.addComponent(buttonPanel, GroupLayout.PREFERRED_SIZE, 756, GroupLayout.PREFERRED_SIZE))
						.addGroup(gl_serverListPanel.createSequentialGroup()
							.addContainerGap()
							.addGroup(gl_serverListPanel.createParallelGroup(Alignment.TRAILING)
								.addComponent(roomInformationPanel, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 954, Short.MAX_VALUE)
								.addComponent(roomInformationAndProgressBarPanel, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 954, Short.MAX_VALUE)
								.addComponent(serverList, Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 954, GroupLayout.PREFERRED_SIZE))
							.addGap(1264)))
					.addContainerGap())
		);
		gl_serverListPanel.setVerticalGroup(
			gl_serverListPanel.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_serverListPanel.createSequentialGroup()
					.addComponent(roomInformationPanel, GroupLayout.PREFERRED_SIZE, 45, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(roomInformationAndProgressBarPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(serverList, GroupLayout.DEFAULT_SIZE, 392, Short.MAX_VALUE)
					.addGap(18)
					.addComponent(buttonPanel, GroupLayout.PREFERRED_SIZE, 62, GroupLayout.PREFERRED_SIZE)
					.addGap(22))
		);
		roomInformationPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
		roomInformationPanel.add(lblNewLabel);
		roomInformationPanel.add(horizontalStrut_1);
		roomInformationPanel.add(lblNewLabel_1);
		roomInformationPanel.add(horizontalStrut_2);
		roomInformationPanel.add(lblNewLabel_2);
		roomInformationPanel.add(horizontalStrut_3);
		roomInformationPanel.add(lblNewLabel_3);
		roomInformationPanel.add(horizontalStrut_4);
		roomInformationPanel.add(lblNewLabel_4);
		roomInformationPanel.add(horizontalStrut_7);
		roomInformationPanel.add(btnUpData);

		btnCreateRoom = new MyJButton();
		btnCreateRoom.setText("创建房间");
		btnCreateRoom.setFont(new Font("新宋体", Font.PLAIN, 22));
		btnCreateRoom.addMouseListener(new CreateRoomActionOfWAN());

		btnJoinRoom = new MyJButton();
		btnJoinRoom.setText("加入房间");
		btnJoinRoom.setFont(new Font("新宋体", Font.PLAIN, 22));

		//界面初始化完毕

		// 添加事件处理

		btnJoinRoom.addMouseListener(new JoinRoomActionOfWAN());

		MyJButton btnBackMainWindow = new MyJButton();
		btnBackMainWindow.setText("\u8FD4\u56DE\u4E3B\u754C\u9762");
		btnBackMainWindow.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				dispose();
				MainWindowUI.getMainFrame().setVisible(true);
			}
		});
		btnBackMainWindow.setFont(new Font("宋体", Font.PLAIN, 22));
		GroupLayout gl_buttonPanel = new GroupLayout(buttonPanel);
		gl_buttonPanel.setHorizontalGroup(
			gl_buttonPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(Alignment.TRAILING, gl_buttonPanel.createSequentialGroup()
					.addComponent(btnCreateRoom, GroupLayout.PREFERRED_SIZE, 131, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED, 183, Short.MAX_VALUE)
					.addComponent(btnJoinRoom, GroupLayout.PREFERRED_SIZE, 138, GroupLayout.PREFERRED_SIZE)
					.addGap(162)
					.addComponent(btnBackMainWindow, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
		);
		gl_buttonPanel.setVerticalGroup(
			gl_buttonPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_buttonPanel.createSequentialGroup()
					.addGap(9)
					.addGroup(gl_buttonPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(btnCreateRoom, GroupLayout.DEFAULT_SIZE, 51, Short.MAX_VALUE)
						.addComponent(btnBackMainWindow, GroupLayout.DEFAULT_SIZE, 50, Short.MAX_VALUE)
						.addComponent(btnJoinRoom, GroupLayout.DEFAULT_SIZE, 52, Short.MAX_VALUE))
					.addContainerGap())
		);
		buttonPanel.setLayout(gl_buttonPanel);
		roomInformationAndProgressBarPanel.setLayout(new BorderLayout(0, 0));
		roomInformationAndProgressBarPanel.add(progressBar);
		serverListPanel.setLayout(gl_serverListPanel);



		JPanel inputServerPanel = new JPanel();
		inputServerPanel.setOpaque(false);
		GroupLayout gl_serverPanel = new GroupLayout(serverPanel);
		gl_serverPanel.setHorizontalGroup(
			gl_serverPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_serverPanel.createSequentialGroup()
					.addGroup(gl_serverPanel.createParallelGroup(Alignment.TRAILING)
						.addComponent(serverListPanel, Alignment.LEADING, 0, 0, Short.MAX_VALUE)
						.addComponent(inputServerPanel, Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 996, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(0, Short.MAX_VALUE))
		);
		gl_serverPanel.setVerticalGroup(
			gl_serverPanel.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_serverPanel.createSequentialGroup()
					.addContainerGap()
					.addComponent(serverListPanel, GroupLayout.DEFAULT_SIZE, 581, Short.MAX_VALUE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(inputServerPanel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
					.addGap(9))
		);
		GroupLayout gl_inputServerPanel = new GroupLayout(inputServerPanel);
		gl_inputServerPanel.setHorizontalGroup(
			gl_inputServerPanel.createParallelGroup(Alignment.LEADING)
				.addGap(0, 996, Short.MAX_VALUE)
		);
		gl_inputServerPanel.setVerticalGroup(
			gl_inputServerPanel.createParallelGroup(Alignment.LEADING)
				.addGap(0, 25, Short.MAX_VALUE)
		);
		inputServerPanel.setLayout(gl_inputServerPanel);
		serverPanel.setLayout(gl_serverPanel);


		JPanel namePanel = new JPanel();
		namePanel.setBackground(Color.WHITE);
		namePanel.setOpaque(false);

		JLabel nameLabel = new JLabel("\u6635\u79F0\uFF1A");
		nameLabel.setFont(new Font("Dialog", Font.BOLD, 20));

		nameTextFiled = new JTextField();
		nameTextFiled.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				contentPane.updateUI();
			}
		});
		nameTextFiled.setText(ClientNameClass.getName());
		nameTextFiled.setBackground(Color.WHITE);
		nameTextFiled.setFont(new Font("Dialog", Font.BOLD, 20));
		nameTextFiled.setColumns(20);

		nextName = new MyJButton();
		nextName.setText("\u968F\u673A");
		nextName.setFont(new Font("Dialog", Font.BOLD, 20));
		GroupLayout gl_namePanel = new GroupLayout(namePanel);
		gl_namePanel.setHorizontalGroup(
			gl_namePanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_namePanel.createSequentialGroup()
					.addGap(84)
					.addComponent(nameLabel, GroupLayout.PREFERRED_SIZE, 75, GroupLayout.PREFERRED_SIZE)
					.addGap(18)
					.addComponent(nameTextFiled, GroupLayout.PREFERRED_SIZE, 232, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(nextName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
					.addGap(359))
		);
		gl_namePanel.setVerticalGroup(
			gl_namePanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_namePanel.createSequentialGroup()
					.addGap(9)
					.addGroup(gl_namePanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(nextName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(nameTextFiled, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(nameLabel, GroupLayout.PREFERRED_SIZE, 34, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
		namePanel.setLayout(gl_namePanel);
		nextName.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {//局域网构造方法
				// TODO Auto-generated method stub
				nameTextFiled.setText(ClientNameClass.getName());
			}
		});
		GroupLayout gl_MainPanel = new GroupLayout(MainPanel);
		gl_MainPanel.setHorizontalGroup(
			gl_MainPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_MainPanel.createSequentialGroup()
					.addGroup(gl_MainPanel.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_MainPanel.createSequentialGroup()
							.addGap(10)
							.addComponent(serverPanel, GroupLayout.PREFERRED_SIZE, 996, GroupLayout.PREFERRED_SIZE))
						.addComponent(namePanel, GroupLayout.PREFERRED_SIZE, 996, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
		gl_MainPanel.setVerticalGroup(
			gl_MainPanel.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_MainPanel.createSequentialGroup()
					.addContainerGap(62, Short.MAX_VALUE)
					.addComponent(namePanel, GroupLayout.PREFERRED_SIZE, 50, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(serverPanel, GroupLayout.PREFERRED_SIZE, 624, GroupLayout.PREFERRED_SIZE)
					.addGap(15))
		);
		MainPanel.setLayout(gl_MainPanel);
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addComponent(MainPanel, GroupLayout.PREFERRED_SIZE, 1014, Short.MAX_VALUE)
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addComponent(MainPanel, GroupLayout.DEFAULT_SIZE, 758, Short.MAX_VALUE)
		);
		contentPane.setLayout(gl_contentPane);
		// 通过局域网，开始收索房间
		client = new ClientDataClass(getNameString(), realLocalIP, 0, MainWindowUI.getID());
		proNumber = 0;
//		searchOfVisitor = new SearchOfVisitor(client);
//		searchOfVisitor.start();
//		searchOfVisitor.sendAskRoomMessage();
		// 当局域网中的IP过滤完一遍或者不需要搜索的时候结束线程
		/**
		 * 隐藏的组件
		 */
	}//构造方法结束


	public static synchronized void showServer(String newserver) {// 把房间的信息显示在list中，因为可能会有多个线程同时调用它，必须用synchronized限制
		vectorServer.add(newserver);
		serverList.updateUI();// 刷新数据
	}
	public static synchronized void showServer(){
		vectorServer.clear();
		for(ServerMessage s : serverMessageVector){
			showServer(s.getHouseOwnerName(), s.getroomNum(), s.getOppNameString(), s.isBegin(),s.getServerAddress().getHostAddress());
		}
	}

	public static synchronized void showServer(String houseName, int roomNum,
			String oppName, boolean isBegin, String ip) {// 把房间的信息显示在list中，因为可能会有多个线程同时调用它，必须用synchronized限制
		
		// 更多详细的变量是方便后期能更好的显示界面
		String allMsg;
		if(roomNum == 1){
			int len=houseName.length();
			allMsg=returnName(houseName)+"  "+roomNum+(returnSpace(12-len)+houseName+returnSpace(12-len))+(isBegin? "正在对战 " : "等待加入 ");
			vectorServer.add("  "+(vectorServer.size()+1) + "  " + allMsg);
		}else if(roomNum > 1) {
			allMsg=returnName(houseName)+"  "+roomNum+returnName(houseName,oppName)+(isBegin? "正在对战 " : "  等待   ");
			vectorServer.add("  "+(vectorServer.size()+1) + "  " + allMsg);
		}
		if(vectorServer.size() == 1)
		{
			serverList.setSelectedIndex(0);
		}
		
		serverList.updateUI();// 刷新数据
		System.out.println("SearchJFrame.showServer()刷新房间列表*******************************************");
	}
	public static String returnSpace(int n){
		String space= new String(" ");
		for(int i=0; i< n-1; i++){
			space +=" ";
		}
		return space;
	}
	

	public static String returnName(String name){
		int len=name.length();
		if(len <= 4){
			name= (returnSpace(5-len)+name+returnSpace(5-len));
		}
		else {
			name =" "+name+" ";
		}
		return name;
	}
	public static String returnName(String name1, String name2){
		int len1=name1.length();
		int len2=name2.length();
		String nameVSname;
		nameVSname=returnSpace(10-len1*2)+ name1+" VS "+name2+returnSpace(10-len2*2);
		return nameVSname;
	}


	public void valueChanged(ListSelectionEvent e) {
		

	}


	public void updateOfRoom(){
		setUpTimeOfNow=System.currentTimeMillis();
		if((setUpTimeOfNow - setUpTime) > 5000){//只能八秒一次
			setUpTime=setUpTimeOfNow;
			vectorServer.clear();
			serverMessageVector.clear();
			serverList.updateUI();// 刷新数据
			proNumber++;
			progressThread = new ProgressThread(progressBar, proNumber);
			progressThread.start();
			if(searchOfVisitor != null){
				searchOfVisitor.sendAskRoomMessage();
			}
			
		}
	}
	class CreateRoomActionOfWAN extends MouseAdapter {
		@Override
		public void mouseClicked(MouseEvent e) {
			System.out
					.println("SearchJFrameOfWAN.CreateRoomActionOfWAN.mouseClicked()");
			client.setClientName(getNameString());
			searchOfVisitor.sendCreateRoom(client);
		}
	}
	class JoinRoomActionOfWAN extends MouseAdapter {
		@Override
		public void mouseClicked(MouseEvent e) {
			System.out
					.println("SearchJFrameOfWAN.JoinRoomActionOfWAN.mouseClicked()");
			int index;
			index = serverList.getSelectedIndex();
			ServerMessage s;
			if (index >= 0) {
				s =serverMessageVector.get(index);
				if (!nameTextFiled.getText().equals("")) {
					client.setClientName(getNameString());
					searchOfVisitor.sendJoinRoom(s, client);
				}else{
					System.out
							.println("SearchJFrameOfWAN.JoinRoomActionOfWAN.mouseClicked()名字不能为空");
				}
			} else {
				System.out.println("服务器列表为空！");
			}
		}	
	}
	
	class UpdataActionOfWAN extends MouseAdapter {
		@Override
		public void mouseClicked(MouseEvent e) {
			System.out
					.println("SearchJFrameOfWAN.UpdataActionOfWAN.mouseClicked()");
			System.out.println("SearchOfVisitor.run()尝试与服务器链接！窗口的状态："+((SearchJFrameOfWAN)MainWindowUI.getSearchframe()).isVisible());
			updateOfRoom();
		}
	}
	class ProgressThread extends Thread{
		boolean isConnect = false;
		boolean isSend = false;
		boolean isReceive = false;
		boolean isEnd= false;
		int timeOut = 10000;//10s超时
		int startTime , now;
		int count = 0;//一共刷新五百次
		int proNum;//用于记录进度条的编号
		JProgressBar progressBar = null;
		public ProgressThread(JProgressBar progressBar, int proNum) {
			// TODO Auto-generated constructor stub
			progressBar.setValue(0);
			this.progressBar = progressBar;
			this.proNum = proNum;
			startTime = (int)System.currentTimeMillis();
			now = (int)System.currentTimeMillis();
		}
		
		public  void setConnect(boolean isConnect) {
			this.isConnect = isConnect;
		}

		public  void setSend(boolean isSend) {
			this.isConnect = true;
			this.isSend = isSend;
		}

		public  void setReceive(boolean isReceive) {
			this.isConnect = true;
			this.isSend = true;
			this.isReceive = isReceive;
		}
		void turnTo(int startPoint, int destination){
			int length = destination - startPoint;
			while (length > 0) {
				if(proNum == proNumber){
					progressBar.setValue(progressBar.getValue() + 1);
					length--;
					try {
						if(length  > 0){
							Thread.sleep(length);
						}
						
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}else{
					break;
				}
			}
			
		}

		public void run() {
			while(! isEnd && (now - startTime ) < timeOut){
				if(isConnect){
					if((proNum == proNumber) && progressBar.getValue() < 50){
						 turnTo(progressBar.getValue(), 50);
					}
					if( isSend ){
						 if((proNum == proNumber) &&progressBar.getValue() < 70){
							 turnTo(progressBar.getValue(), 70);
						} 
						 if(isReceive){
							 isEnd = true;
							 if((proNum == proNumber) &&progressBar.getValue() <= 100){
								 turnTo(progressBar.getValue(), 100);
								}
						 }else {//发送出去但没收到
							 if(proNum == proNumber){
								 progressBar.setValue(70 + count / 20);
							 }
						 }
					 }else if((proNum == proNumber) && progressBar.getValue() <= 70){//连上没发送成功
						 progressBar.setValue(50 + count / 25);
					 }
				}else if((proNum == proNumber) && progressBar.getValue() <= 50){//没连上
					progressBar.setValue(count / 10);
				 }
				try {
					Thread.sleep(timeOut / 500);
					now = (int)System.currentTimeMillis();
					count ++;
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			try {
				Thread.sleep(100);
				if(proNum == proNumber){
				progressBar.setValue(0);
				}
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}


